package demo.springcloud.webflux.rest.controller;

import demo.springcloud.webflux.common.entity.PageResult;
import demo.springcloud.webflux.common.entity.Result;
import demo.springcloud.webflux.common.entity.StatusCode;
import demo.springcloud.webflux.common.utils.JwtUtil;
import demo.springcloud.webflux.rest.entity.User;
import demo.springcloud.webflux.rest.exceptions.ResourceNotFoundException;
import demo.springcloud.webflux.rest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
    @ExceptionHandler(ResourceNotFoundException.class)
    public void notFound() {
    }

//    @GetMapping("")
//    public Flux<User> list() {
//        return userService.list();
//    }

    @GetMapping("")
    public Result list() {
        PageResult p = userService.list2();
        return new Result(true, StatusCode.OK, "查询成功", p);
    }

//    @GetMapping("/{id}")
//    public Mono<User> getById(@PathVariable String id) {
//        return userService.getById(id);
//    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        User user = userService.getById2(id);
        return new Result(true, StatusCode.OK, "查询成功", user);
    }

//    @PostMapping("")
//    public Mono<User> create(@RequestBody User user, HttpHeaders headers) {
//        return userService.createOrUpdate(user);
//    }

    @PostMapping("")
    public Result create(@RequestBody User user, ServerWebExchange exchange) {
        String userId = exchange.getAttribute("userId");
        if(null == userId) {
            return new Result(false, StatusCode.LOGINERROR, "请先登录");
        }
        User user2 = userService.createOrUpdate2(user);
        return new Result(true, StatusCode.OK, "添加成功", user2);
    }

    @DeleteMapping("/{id}")
    public Mono<User> deleteById(@PathVariable String id) {
        return userService.delete(id);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String token = jwtUtil.createJWT(user.getId(), user.getName(), "user");

        Map map=new HashMap();
        map.put("token",token);
        return new Result(true, StatusCode.OK, "登录成功", map);
    }

    @GetMapping("/hystrix")
    public Mono<String> hystrix() {

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return Mono.just("睡醒了");
    }
}
